import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Message} from 'primeng/primeng';
import {DutyService} from '../duty.service';
import {ActivatedRoute, Router} from '@angular/router';

@Component({
  selector: 'app-schedule-approval',
  templateUrl: './schedule-approval.component.html',
  styleUrls: ['./schedule-approval.component.scss']
})
export class ScheduleApprovalComponent implements OnInit {

    beginTime: Date;                       // 开始时间
    endTime: Date;                         // 结束时间
    shiftSelectedMultipleOption: any[];    // 排班班次已选数据
    relativeSelectedMultipleOption: any[]; // 关联计划已选数据
    approveSelectedMultipleOption: any[];  // 审批人已选数据
    defaultId: string;                     // 新增排班编号
    defaultCreator: string;                // 新增排班创建人
    defaultCreateTime: string;             // 新增排班创建时间
    defaultName: string;                   // 计划名称
    newSchdule: FormGroup;
    formBuilder: FormBuilder = new FormBuilder();
    msgs: Message[] = [];                  // 表单验证提示
    msgPop: Message[] = [];                // 提示弹出框
    apporvalSuggestion: string;            // 审批意见
    progressBar: boolean;                  // 进度条
    currentSheduleId;                      // 当前计划ID
    selectedDepartment = '';               // 表单显示的已选中的部门组织
    whichOprate: string;                   // 操作类型
    dialogdisplay: boolean;                 // 是否显示模态框
    dispalyError: boolean = false;
    myForm: FormGroup;

    constructor(private dutyService: DutyService,
                private activitedRoute: ActivatedRoute,
                private router: Router) {
    }

    ngOnInit() {
        this.initForm();
        this.dialogdisplay = false;
        this.currentSheduleId = this.activitedRoute.snapshot.paramMap.get('id');
        this.dutyService.getScheduleById(this.currentSheduleId).subscribe(res => {
            this.defaultId = res.did;
            this.defaultCreator = res.creator;
            this.defaultName = res.name;
            this.newSchdule.get('schduleName').setValue(res.name);
            this.defaultCreateTime = res.create_time;
            let departArray = [];
            res['orgs_structures'].forEach(function(data) {
                departArray.push(data['name']);
            });
            this.selectedDepartment = String(departArray);
            this.beginTime = res['begin_time'];
            this.endTime = res.end_time;
            this.approveSelectedMultipleOption = res['approver'];
            this.shiftSelectedMultipleOption = res['shifts_name'];
            this.relativeSelectedMultipleOption = res['related_duty'];
            this.apporvalSuggestion = res.approve_remarks;
        });
        this.progressBar = true;
        this.beginTime = new Date();
        this.endTime = new Date();
        this.createForm();
    }
    initForm() {
        this.myForm = this.formBuilder.group({
           apporvalSuggestion: [null, Validators.required]
        });
    }
    isFieldValid(field: string) {
        return !this.myForm.get(field).valid && this.myForm.get(field).touched;
    }
    validateAllFormFields(formGroup: FormGroup) {
        Object.keys(formGroup.controls).forEach(field => {
            const control = formGroup.get(field);
            if (control instanceof FormControl) {
                control.markAsTouched({onlySelf: true});
            }else if (control instanceof  FormGroup) {
                this.validateAllFormFields(control);
            }
        });
    }
    createForm() {
        this.newSchdule = this.formBuilder.group({
            schduleName: ['', Validators.required],
            scheduleApprovor: [this.approveSelectedMultipleOption, Validators.required],
            scheduleId: [this.defaultId, Validators.required],
            scheduleCreator: [this.defaultCreator, Validators.required],
            scheduleCreateTime: [this.defaultCreateTime, Validators.required]
        });
    }
    oporate(oporate: string) {
        this.whichOprate = oporate;
        this.dialogdisplay = true;
    }
    pass() {
        // this.validateAllFormFields(this.myForm);
      this.approvalSchedule('待执行');
    }
    return() {
        if (this.apporvalSuggestion){
            this.approvalSchedule(this.whichOprate);
            this.dialogdisplay = false;
        }else {
            this.validateAllFormFields(this.myForm);
            this.dialogdisplay = false;
        }
    }
    showError() {
        this.msgPop = [];
        this.msgPop.push({severity: 'error', summary: '错误消息提示', detail: this.whichOprate + '失败'});
    }
    showSucc() {
        this.msgPop = [];
        this.msgPop.push({severity: 'success', summary: '成功消息提示', detail: this.whichOprate + '成功'});
        window.setTimeout(() => {
          this.router.navigateByUrl('index/duty/manage');
        }, 3000);
    }
    approvalSchedule(status: string) {
        this.dutyService.approveSchedule(this.defaultId, this.apporvalSuggestion, status).subscribe(res => {
            if (res){
                this.showSucc();
            }else{
                this.showError();
            }

        });
    }

}
